package com.zyt.thymeleaf.controller;

import com.zyt.thymeleaf.mapper.ArticleMapper;
import com.zyt.thymeleaf.pojo.Article;
import com.zyt.thymeleaf.pojo.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @author zyt
 * @createDate 2020/05/20 4:08 PM
 */
@Controller
public class IndexController {
    @Autowired
    private ArticleMapper articleMapper;

    @RequestMapping("/test")
    @ResponseBody
    public String test(Model model) {
        return "test";
    }

    @RequestMapping("/index")
    public String index(Model model, @RequestParam(required = false) Integer page) {
        //每页数量
        int pageSize = 3;
        //总记录数
        int total = articleMapper.selectCount();
        //总页数
        int totalPage = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;

        //处理当前页
        int pageNo;
        if (null == page || page <= 0) {
            pageNo = 1;
        } else if (page > totalPage) {
            pageNo = totalPage;
        } else {
            pageNo = page;
        }


        Page pageParam = new Page();
        pageParam.setOffset(pageSize * (pageNo - 1));
        pageParam.setPageSize(pageSize);
        List<Article> articles = articleMapper.selectList(pageParam);

        model.addAttribute("articles", articles);
        model.addAttribute("pageNo", pageNo);
        model.addAttribute("totalPage", totalPage);
        return "client/index";
    }
}
